//用户相关的数据
import { createSlice } from "@reduxjs/toolkit";
import { setToken as _setToken,getToken, removeToken } from "@/utils";
import {getTokenAPI,getUserInfoAPI} from '@/apis/UserApi'

const userStore  = createSlice({
    //名称
    name: "user",
    //数据状态
    initialState:{
        //【2】在初始化的时候先确认下是否存在token
        token : getToken() || '',
        userInfo :{}
    },

    //同步处理方法
    reducers:{ 
        //设置token
        setToken(state,action){
            state.token = action.payload
            //【1】在localStorage中存储一份
            _setToken(action.payload)
        },
        //设置用户信息
        setUserInfo(state,action){
            state.userInfo =action.payload
        },
        //清除用户信息
        clearUserInfo(state){
            state.token =''
            state.userInfo ={}
            removeToken()
        }
        
    }
})

//获取CreateAction方法
const {setToken,setUserInfo,clearUserInfo} = userStore.actions

//异步处理方法

const fetchLogin =(values)=>{
    return  async (dispatch)=>{
        const  res = await  getTokenAPI(values)
        dispatch(setToken(res.data.data.token))
     
    }
}

//异步方式获取用户信息
const fetchUserInfo=()=>{
   return  async (dispatch)=>{
        const res = await getUserInfoAPI()
        dispatch(setUserInfo(res.data.data))
    }
}
export {fetchLogin,fetchUserInfo,clearUserInfo}

//获取reducer 
const userReducer  =  userStore.reducer

export default userReducer